from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
# from rest_framework.generics import GenericAPIView
from rest_framework.generics import CreateAPIView
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from rest_framework_jwt.settings import api_settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

from carts.utils import merge_cart_cookie_to_redis
from oauth.models import OAuthQQUser
from oauth.serializers import OauthSerializer


class QQLoginURLView(APIView):
    '''
    构建跳转链接
    '''

    def get(self, request):
        state = request.query_params.get('next')
        if state is None:
            state = '/'

        # 1,生成qq对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        # 2, 调用生成url的方法
        login_url = qq.get_qq_url()

        # 3,返回url
        return Response({'login_url': login_url})


class OauthView(CreateAPIView):
    '''
    获取openid和绑定openid
    '''
    serializer_class = OauthSerializer

    def get(self, request):

        # 1,获取前端传递的code
        code = request.query_params.get('code')
        if code is None:
            return Response({'errors': '缺少code值'}, status=400)

        # 2,通过code值请求qq服务器获取access_token值
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state='/')

        access_token = qq.get_access_token(code)

        # 3,通过access_token值请求qq服务器获取openid值
        openid = qq.get_open_id(access_token)

        # 4,判断openid和美多用户是否绑定
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except:

            # 5,未绑定，绑定openid
            tjs = TJS(settings.SECRET_KEY, 300)

            # data = tjs.dumps({'openid':openid}).decode()
            data = tjs.dumps({'openid': openid}).decode()

            return Response({'access_token': data})

        # 6,如果绑定过则登录成功
        else:

            # 获取用户对象
            user = qq_user.user

            # 生成jwt token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response=Response({
                'token': token,
                'username': user.username,
                'user_id': user.id
            })

            # 合并购物车
            response = merge_cart_cookie_to_redis(request,response,user)

            return response

            # def post(self,request):
            #     user
